// pages/setaddress/setaddress.js
var QQMapWX = require('../../qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min');
var qqmapsdk;
const app = getApp()
import {userAddressAddModify,userAddressDfault,userAddressDelete} from '../../api/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageName: '编辑收获地址',
    list: [{
        title: '收货人',
        del: 1,
        type: 'text',
        placeholder: '姓名',
        value: ''
      },
      {
        title: '联系方式',
        del: 1,
        type: 'number',
        placeholder: '手机号码',
        value: ''
      },
      {
        title: '所在地区',
        del: 0,
        type: 'text',
        placeholder: '省市区县、乡镇等',
        value: ''
      },
      {
        title: '详细地址',
        del: 1,
        type: 'text',
        placeholder: '街道、楼牌号等',
        value: ''
      }
    ],
    switch: false,
    submit: {
      token: app.globalData.userInfo.token,
      phone: '',
      procince: '',
      city: '',
      area: '',
      name: '',
      detailed: '',
    },
    address_id: '',
    region: [],
    customItem: '全部',
    isnew: true,
    page:'',
    error:''
  },
  //删除地址
  delAddress(){
    userAddressDelete({
      token:app.globalData.userInfo.token,
      id:this.data.address_id
    }).then(res=>{
      wx.navigateBack({
        delta: 1,
      })
    })
  },
  //提交
  submitInfo(){
    console.log(this.data.page);
    let name='submit.name'
    let phone='submit.phone'
    let detail='submit.detailed'
    this.setData({
      [name]:this.data.list[0].value,
      [phone]:this.data.list[1].value,
      [detail]:this.data.list[3].value
    })
    console.log(this.data);
    if(this.data.page=='edit'){
      let address_id='submit.address_id'
      this.setData({
        [address_id]:this.data.address_id
      })
    }
    userAddressAddModify(this.data.submit).then(res=>{
      console.log(res);
      this.setData({
        error:res.msg
      })
      // if(res.code==2000){
        if(this.data.switch){
          if(this.data.page=='edit'){
            userAddressDfault({
              token:app.globalData.userInfo.token,
              id:this.data.address_id
            }).then(res=>{
              wx.navigateBack({
                delta: 1,
              })
            })
          }else{
            userAddressDfault({
              token:app.globalData.userInfo.token,
              id:res.other.add_address_id
            }).then(res=>{
              wx.navigateBack({
                delta: 1,
              })
            })
          }
          
        }else{
          wx.navigateBack({
            delta: 1,
          })
        }
      // }else{
      //   this.setData({
      //     error:res.msg
      //   })
      // }
    })
  },
  //picker 省市区
  bindRegionChange: function (e) {
    console.log('picker发送选择改变，携带值为', e)
    let key1 = 'list[2].value'
    let procince = 'submit.procince'
    let city = 'submit.city'
    let area = 'submit.area'
    this.setData({
      [key1]: `${e.detail.value[0]} ${e.detail.value[1]} ${e.detail.value[2]}`,
      region: e.detail.value,
      [procince]: e.detail.code[2].slice(0, 2),
      [city]: e.detail.code[2].slice(2, 4),
      [area]: e.detail.code[2].slice(4)
    })
    console.log(this.data.submit);
  },
  goMap() {
    wx.redirectTo({
      url: '/pages/map/map?name='+this.data.list[0].value+'&&phone='+this.data.list[1].value+'page='+this.data.page
    })
  },
  //编辑input框
  input(e) {
    // e.detail.value
    // e.target.dataset
    let index = this.data.list.findIndex(item => item.title == e.target.dataset.item.title)
    let key = `list[${index}].value`
    console.log(key);
    this.setData({
      [key]: e.detail.value
    })
  },
  //清空input框
  delinput(e) {
    let index = this.data.list.findIndex(item => item.title == e.target.dataset.item.title)
    let key = `list[${index}].value`
    this.setData({
      [key]: ''
    })
  },
  switchchange(e) {
    console.log(e.detail.value);
    this.setData({
      switch: e.detail.value
    })
  },
  //逆解析地址
  reverse(obj) {
    qqmapsdk.reverseGeocoder({
      //位置坐标，默认获取当前位置，非必须参数
      /**
       * 
       //Object格式
        location: {
          latitude: 39.984060,
          longitude: 116.307520
        },
      */
      /**
       *
       //String格式
        location: '39.984060,116.307520',
      */
      location: obj, //获取表单传入的位置坐标,不填默认当前位置,示例为string格式
      get_poi: 1, //是否返回周边POI列表：1.返回；0不返回(默认),非必须参数
      success: (res) => { //成功后的回调
        console.log(res);
        let result = res.result;
        let key1 = 'list[2].value'
        let procince = 'submit.procince'
        let city = 'submit.city'
        let area = 'submit.area'
        this.setData({
          [key1]: `${result.address_component.province} ${result.address_component.city} ${result.address_component.district}`,
          [procince]: result.ad_info.adcode.slice(0, 2),
          [city]: result.ad_info.adcode.slice(2, 4),
          [area]: result.ad_info.adcode.slice(4)
        })
        console.log(this.data.submit);
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {}
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      page:options.page
    })
    qqmapsdk = new QQMapWX({
      key: '3ETBZ-4E56U-GY6VO-BIO5W-BBPZ6-HGFUH'
    });
    if (options.pages == 'map') {
      let str = JSON.parse(options.str)
      let key2 = 'list[3].value'
      let name='list[0].value'
      let phone='list[1].value'
      this.setData({
        [key2]: str.title,
        [name]:options.name,
        [phone]:options.phone
      })
      this.reverse({
        latitude: str.latitude,
        longitude: str.longitude
      })
      return
    }
    if (options.page == 'new') {
      this.setData({
        isnew: false,
        switch: false
      })
    }
    if (options.page == 'edit') {
      let str=JSON.parse(options.str)
      let name='list[0].value'
      let phone='list[1].value'
      let area='list[2].value'
      let detail='list[3].value'
      let submitP='submit.procince'
      let submitC='submit.city'
      let submitA='submit.area'
      this.setData({
        isnew:false,
        address_id:str.address_id,
        switch:str.default,
        [name]:str.name,
        [phone]:str.phone,
        [area]:`${str.procince_text} ${str.city_text} ${str.area_text}`,
        [detail]:str.detailed,
        [submitP]:str.procince,
        [submitC]:str.city,
        [submitA]:str.area,
      })
      
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})